package com.yyw.Service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yyw.bean.Word;
import com.yyw.dao.WordDao;
import com.yyw.util.Result;
import com.yyw.util.ResultFactory;

@Service
public class WordService {

    @Autowired
    private WordDao wordDao;

    /**
     * 保存单词
     *
     * @param word
     * @return
     */
    public Result saveWord(Word word) {
        // 数据校验
        if (StringUtils.isEmpty(word.getWord()) || StringUtils.isEmpty(word.getContent())) {
            return ResultFactory.notice("数据不合法");
        }

        int result = wordDao.saveWord(word);
        if (result > 0) {
            return ResultFactory.success("添加成功");
        } else {
            return ResultFactory.failure("添加失败");
        }
    }

    /**
     * 分页查询获取单词，按照创建时间降序
     *
     * @param pageNo
     * @param pageNum
     * @return
     */
    public Result getWords(Integer pageNo, Integer pageNum) {
        if (pageNo == null || (pageNo < 1)) {
            return ResultFactory.notice("页数不合法");
        }
        if (pageNum == null || pageNum < 1) {
            return ResultFactory.notice("每页数量不合法");
        }

        PageHelper.startPage(pageNo, pageNum);
        List<Word> words = wordDao.getWords();
        PageInfo<Word> pageInfo = new PageInfo<>(words);

        return ResultFactory.success(pageInfo);
    }
}
